<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--货品类别数据-->
        <pane size="16">
          <el-col>
            <div class="head-container">
              <el-input v-model="categoryName" placeholder="请输入类别名称" clearable size="small" prefix-icon="el-icon-search"
                style="margin-bottom: 20px" />
            </div>
            <div class="head-container">
              <el-tree :data="categoryOptions" :props="defaultProps" :expand-on-click-node="false"
                :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
                @node-click="handleNodeClick" />
            </div>
          </el-col>
        </pane>
        <!--货品数据-->
        <pane size="84">
          <el-col>
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
              label-width="68px">
              <el-form-item label="货品代码" prop="goodsCode">
                <el-input v-model="queryParams.goodsCode" placeholder="请输入货品代码" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="品名规格" prop="goodsSpec">
                <el-input v-model="queryParams.goodsSpec" placeholder="请输入品名规格" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="供应商品名" prop="supplyGoodsName">
                <el-input v-model="queryParams.supplyGoodsName" placeholder="请输入供应商品名" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="货品类别ID" prop="goodsCategoryId">
                <el-input v-model="queryParams.goodsCategoryId" placeholder="请输入货品类别ID" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="主计量单位" prop="primaryUnit">
                <el-input v-model="queryParams.primaryUnit" placeholder="请输入主计量单位" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="辅助单位" prop="secondaryUnit">
                <el-input v-model="queryParams.secondaryUnit" placeholder="请输入辅助单位" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="换算率" prop="conversionRate">
                <el-input v-model="queryParams.conversionRate" placeholder="请输入换算率" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="库存数量" prop="stockQuantity">
                <el-input v-model="queryParams.stockQuantity" placeholder="请输入库存数量" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="期初成本" prop="initialCost">
                <el-input v-model="queryParams.initialCost" placeholder="请输入期初成本" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="进货价" prop="purchasePrice">
                <el-input v-model="queryParams.purchasePrice" placeholder="请输入进货价" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="零售价" prop="retailPrice">
                <el-input v-model="queryParams.retailPrice" placeholder="请输入零售价" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="批发价1" prop="wholesalePrice1">
                <el-input v-model="queryParams.wholesalePrice1" placeholder="请输入批发价1" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="批发价2" prop="wholesalePrice2">
                <el-input v-model="queryParams.wholesalePrice2" placeholder="请输入批发价2" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="最高库存" prop="maxStock">
                <el-input v-model="queryParams.maxStock" placeholder="请输入最高库存" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="最低库存" prop="minStock">
                <el-input v-model="queryParams.minStock" placeholder="请输入最低库存" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                  v-hasPermi="['business:goods:add']">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                  v-hasPermi="['business:goods:edit']">修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                  @click="handleDelete" v-hasPermi="['business:goods:remove']">删除</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
                  v-hasPermi="['business:goods:import']">导入</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                  v-hasPermi="['business:goods:export']">导出</el-button>
              </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>

            <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="自增长主键" align="center" prop="id" />
              <el-table-column label="货品代码" align="center" prop="goodsCode" />
              <el-table-column label="货品图片" align="center" width="100">
                <template slot-scope="scope">
                  <el-image v-if="scope.row.goodsImage" :src="getImageUrl(scope.row.goodsImage)" style="width: 60px; height: 60px"
                    :preview-src-list="[getImageUrl(scope.row.goodsImage)]">
                  </el-image>
                  <div v-else class="image-placeholder">
                    <i class="el-icon-picture-outline" style="font-size: 24px;"></i>
                    <div style="font-size: 12px; margin-top: 5px;">暂无图片</div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="品名规格" align="center" prop="goodsSpec" />
              <el-table-column label="供应商品名" align="center" prop="supplyGoodsName" />
              <el-table-column label="货品类别ID" align="center" prop="goodsCategoryId" />
              <el-table-column label="主计量单位" align="center" prop="primaryUnit" />
              <el-table-column label="辅助单位" align="center" prop="secondaryUnit" />
              <el-table-column label="换算率" align="center" prop="conversionRate" />
              <el-table-column label="库存数量" align="center" prop="stockQuantity" />
              <el-table-column label="期初成本" align="center" prop="initialCost" />
              <el-table-column label="进货价" align="center" prop="purchasePrice" />
              <el-table-column label="零售价" align="center" prop="retailPrice" />
              <el-table-column label="批发价1" align="center" prop="wholesalePrice1" />
              <el-table-column label="批发价2" align="center" prop="wholesalePrice2" />
              <el-table-column label="最高库存" align="center" prop="maxStock" />
              <el-table-column label="最低库存" align="center" prop="minStock" />

              <el-table-column label="备注" align="center" prop="remark" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                    v-hasPermi="['business:goods:edit']">修改</el-button>
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                    v-hasPermi="['business:goods:remove']">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize" @pagination="getList" />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>

    <!-- 添加或修改货品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="货品代码" prop="goodsCode">
          <el-input v-model="form.goodsCode" placeholder="请输入货品代码" />
        </el-form-item>
        <el-form-item label="品名规格" prop="goodsSpec">
          <el-input v-model="form.goodsSpec" placeholder="请输入品名规格" />
        </el-form-item>
        <el-form-item label="供应商品名" prop="supplyGoodsName">
          <el-input v-model="form.supplyGoodsName" placeholder="请输入供应商品名" />
        </el-form-item>
        <el-form-item label="货品类别" prop="goodsCategoryId">
          <treeselect v-model="form.goodsCategoryId" :options="categoryOptions" :normalizer="normalizer"
            :show-count="true" placeholder="请选择货品类别" />
        </el-form-item>
        <el-form-item label="主计量单位" prop="primaryUnit">
          <el-input v-model="form.primaryUnit" placeholder="请输入主计量单位" />
        </el-form-item>
        <el-form-item label="辅助单位" prop="secondaryUnit">
          <el-input v-model="form.secondaryUnit" placeholder="请输入辅助单位" />
        </el-form-item>
        <el-form-item label="换算率" prop="conversionRate">
          <el-input v-model="form.conversionRate" placeholder="请输入换算率" />
        </el-form-item>
        <el-form-item label="库存数量" prop="stockQuantity">
          <el-input v-model="form.stockQuantity" placeholder="请输入库存数量" />
        </el-form-item>
        <el-form-item label="期初成本" prop="initialCost">
          <el-input v-model="form.initialCost" placeholder="请输入期初成本" />
        </el-form-item>
        <el-form-item label="进货价" prop="purchasePrice">
          <el-input v-model="form.purchasePrice" placeholder="请输入进货价" />
        </el-form-item>
        <el-form-item label="零售价" prop="retailPrice">
          <el-input v-model="form.retailPrice" placeholder="请输入零售价" />
        </el-form-item>
        <el-form-item label="批发价1" prop="wholesalePrice1">
          <el-input v-model="form.wholesalePrice1" placeholder="请输入批发价1" />
        </el-form-item>
        <el-form-item label="批发价2" prop="wholesalePrice2">
          <el-input v-model="form.wholesalePrice2" placeholder="请输入批发价2" />
        </el-form-item>
        <el-form-item label="最高库存" prop="maxStock">
          <el-input v-model="form.maxStock" placeholder="请输入最高库存" />
        </el-form-item>
        <el-form-item label="最低库存" prop="minStock">
          <el-input v-model="form.minStock" placeholder="请输入最低库存" />
        </el-form-item>
        <el-form-item label="货品图片" prop="goodsImage">
          <image-upload
            v-model="form.goodsImage"
            :limit="3"
            :fileSize="2"
            :fileType="['jpg', 'jpeg', 'png']"
            :isShowTip="true"
            class="compact-upload"
          />
          <div class="el-upload__tip">建议上传高清商品照片，以提升客户体验</div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 货品导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的货品数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listGoods, getGoods, delGoods, addGoods, updateGoods, listCategory, importGoods } from "@/api/business/goods";
import { getToken } from "@/utils/auth";
import { getImageUrl } from "@/utils/image";
import { Splitpanes, Pane } from "splitpanes";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import "splitpanes/dist/splitpanes.css";
import ImageUpload from "@/components/ImageUpload";

export default {
  name: "Goods",
  components: { Splitpanes, Pane, Treeselect, ImageUpload },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 货品信息表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsCode: null,
        goodsSpec: null,
        supplyGoodsName: null,
        goodsCategoryId: null,
        primaryUnit: null,
        secondaryUnit: null,
        conversionRate: null,
        stockQuantity: null,
        initialCost: null,
        purchasePrice: null,
        retailPrice: null,
        wholesalePrice1: null,
        wholesalePrice2: null,
        maxStock: null,
        minStock: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        goodsCode: [
          { required: true, message: "货品代码不能为空", trigger: "blur" }
        ],
        goodsSpec: [
          { required: true, message: "品名规格不能为空", trigger: "blur" }
        ],
        goodsCategoryId: [
          { required: true, message: "货品类别不能为空", trigger: "blur" }
        ]
      },
      // 货品类别名称
      categoryName: undefined,
      // 货品类别树选项
      categoryOptions: undefined,
      // 默认树属性
      defaultProps: {
        children: "children",
        label: "categoryName"
      },
      // 货品导入参数
      upload: {
        // 是否显示弹出层（货品导入）
        open: false,
        // 弹出层标题（货品导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的货品数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/business/goods/importData",
        // 图片上传地址
        imageUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      },
    };
  },
  watch: {
    // 根据名称筛选货品类别树
    categoryName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getCategoryTree();
  },
  methods: {
    /** 查询货品类别树结构 */
    getCategoryTree() {
      listCategory().then(response => {
        this.categoryOptions = this.handleTree(response.data, "id", "parentId");
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.categoryName.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.goodsCategoryId = data.id;
      this.handleQuery();
    },
    /** 查询货品信息列表 */
    getList() {
      this.loading = true;
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        goodsCode: null,
        goodsSpec: null,
        supplyGoodsName: null,
        goodsCategoryId: null,
        primaryUnit: null,
        secondaryUnit: null,
        conversionRate: null,
        stockQuantity: null,
        initialCost: null,
        purchasePrice: null,
        retailPrice: null,
        wholesalePrice1: null,
        wholesalePrice2: null,
        maxStock: null,
        minStock: null,
        remark: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.goodsCategoryId = undefined;
      this.$refs.tree && this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 转换货品类别数据结构 */
    normalizer(node) {
      return {
        id: node.id,
        label: node.categoryName,
        children: node.children
      };
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getCategoryTree();
      this.open = true;
      this.title = "添加货品信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getCategoryTree();
      const id = row.id || this.ids
      getGoods(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改货品信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateGoods(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoods(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除货品信息编号为"' + ids + '"的数据项？').then(function () {
        return delGoods(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/goods/export', {
        ...this.queryParams
      }, `goods_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "货品导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('business/goods/importTemplate', {}, `goods_template_${new Date().getTime()}.xlsx`);
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    handleUploadSuccess(res, file, type) {
      console.log(res)
      if (res.code === 200) {
        const imageUrl = res.url || process.env.VUE_APP_BASE_API + res.fileName

        if (!this.form[type]) {
          this.$set(this.form, type, [])
        }

        this.form[type].push({ name: res.fileName, url: imageUrl })

        this.form[type] = [...this.form[type]]
      } else {
        this.$message.error('上传失败：' + res.msg)
      }
    },
    handleRemove(file, fileList, type) {
      this.form[type] = fileList
    },
    getImageUrl
  }
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}

/* 保留占位符样式 */
.image-placeholder {
  width: 60px;
  height: 60px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  color: #909399;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  margin: 0 auto;
}
</style>
